//
//  PKPlayerManager.m
//  AVPlayer
//
//  Created by lanou on 15/10/5.
//  Copyright (c) 2015年 完美的宇gogo. All rights reserved.
//

#import "PKPlayerManager.h"
#import <AVFoundation/AVFoundation.h>

@interface PKPlayerManager ()

// 用来保存音乐地址的数组
@property (nonatomic, strong) NSArray *musicArray;

// 音乐播放器
@property (nonatomic, strong) AVPlayer *avPlayer;

// 当前播放的音乐下标
@property (nonatomic, assign) NSInteger currentIndex;

@end



@implementation PKPlayerManager


- (instancetype)init
{
    self = [super init];
    if (self)
    {
        _avPlayer = [[AVPlayer alloc]init];
    }
    return self;
}


+ (instancetype)shareManager
{
    static PKPlayerManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[PKPlayerManager alloc]init];
    });
    return manager;
}

// 播放地址的数组
- (void)setManagerMusicArray:(NSArray *)array
{
    _musicArray = array;
}

// 根据外界传过来的下标来播放音乐
- (void)playWithIndex:(NSInteger)index
{
    _currentIndex = index;
    // 根据外界传过来的下标选择数组里响应的播放地址
    NSURL *musicURL = [NSURL URLWithString:_musicArray[index]];
    AVPlayerItem *avPlayerItem = [[AVPlayerItem alloc]initWithURL:musicURL];
    // 把播放器的播放地址替换成新的地址
    [_avPlayer replaceCurrentItemWithPlayerItem:avPlayerItem];
    [_avPlayer play];
    
}


// 下一首
- (void)nextMusic
{
    _currentIndex++;
    if (_currentIndex == _musicArray.count)
    {
        _currentIndex = 0;
    }
    // 判断如果是随机播放就随机一个播放下标
    if (_playType == PlayTypeRandom)
    {
        _currentIndex = arc4random() % _musicArray.count;
    }
    
    [self playWithIndex:_currentIndex];
}

// 上一首
- (void)lastMusic
{
    _currentIndex--;
    if (_currentIndex < 0)
    {
        _currentIndex = _musicArray.count - 1;
    }
    // 判断如果是随机播放就随机一个播放下标
    if (_playType == PlayTypeRandom)
    {
        _currentIndex = arc4random() % _musicArray.count;
    }
    [self playWithIndex:_currentIndex];
}

// 播放和暂停
- (void)playAndPause
{
    // 判断AVPlayer当前的状态，0.0代表停止播放状态，1.0代表正在播放状态
    if (_avPlayer.rate == 0.0)
    {
        [_avPlayer play];
    }
    else
    {
        [_avPlayer pause];
    }
}

- (NSUInteger)finishTime
{
    
    CMTime time = _avPlayer.currentItem.duration;
    // 判断time.timescale是否为0，若为0，表示还未开始下载，即网络不好。若不进行判断，当网络不好时，time.timescale为0，则系统会崩溃，因为time.value / time.timescale分母不能为0
    if (time.timescale == 0)
    {
        return 0;
    }
    return time.value / time.timescale;
}

- (NSUInteger)currentTime
{
    CMTime time = _avPlayer.currentTime;
    if (time.timescale == 0)
    {
        return 0;
    }
    return time.value / time.timescale;
}

// 跳转
- (void)seekToTime:(NSUInteger)time
{
    CMTime newTime = _avPlayer.currentTime;
    // 秒 = value / 基数
    newTime.value = time * newTime.timescale;
    [_avPlayer seekToTime:newTime];
}

// 停止播放
- (void)stop
{
    [self seekToTime:0];
    [_avPlayer pause];
}

@end
